import React ,{Component}from "react";
import {Card,Form, Input, Button, Checkbox,message} from 'antd'
import styles from './index.module.scss'
import logo from '../../assets/logo.png'
import { login } from "../../api/use";
import { setToken } from "../../utils/storage";
console.log(styles)



class Login extends Component{
    state={
        loading:false,
    }

    onFinish= async ({mobile,code})=>{
        this.setState({
            loading:true
        })
        try{
    const res=await login(mobile,code)
       //3.提示信息
       message.success('登陆成功',1,()=>{
        //登录成功
       //1.保存token
       //localStorage.setItem('token',res.data.token)
       setToken(res.data.token)
       //2.跳转到首页
       this.props.history.push('/home')

       })
        }catch(error){
            message.warning(error.response.data.message,1,()=>{
                this.setState({
                    loading:false
                })
            })


        }
       
    }

    render(){
        return(
            <div className={styles.login}>
            <Card className="login-container">
                <img src={logo} alt="" className="login-logo"/>
                {/* 表单 */}
                <Form name="basic" size="large"
                 validateTrigger={['onChange','onBlur']}
                 onFinish={this.onFinish}
                 initialValues={{
                     agree:true,
                     mobile:'13811111111',
                     code:'246810'
                 }}
                >
      <Form.Item name="mobile"
        rules={
            [
                {
                    pattern:/^1[3-9]\d{9}$/,
                    message:'手机号码格式不对'
                },
                {required:true,message:'请输入手机号'},
            ]
        }
      >
        <Input placeholder="请输入手机号"/>
      </Form.Item>

      <Form.Item name="code"
        rules={
            [
                {
                    pattern: /^\d{6}$/,
                    message: '验证码格式不对',
                },
                { required: true, message: '请输入验证码' },
            ]
        }
      >
        <Input placeholder="请输入验证码" />
      </Form.Item>

      <Form.Item 
      name="agree" 
      valuePropName="checked"
      rules={[{
          //自定义校验规则
          validator(rule,value){
              if(value){
                  return Promise.resolve()
              }else{
                  return Promise.reject(new Error('请阅读并同意用户协议'))
              }
          }
        }]}
      >
        <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit"  loading={this.state.loading}>
          登录登录
        </Button>
      </Form.Item>
                </Form>
             </Card>
          </div>
        )

    }
}


export default Login